package com.happok.onlineclass.usermanagement.authentication.config;

import com.happok.onlineclass.usermanagement.authentication.config.authentication.SmsCodeAuthenticationSecurityConfig;
import com.happok.onlineclass.usermanagement.authentication.config.filter.ValidateCodeFilter;
import com.happok.onlineclass.usermanagement.authentication.config.handler.MyAuthenticationFailureHandler;
import com.happok.onlineclass.usermanagement.authentication.service.HappokRememberMeServices;
import com.happok.onlineclass.usermanagement.authentication.service.RememberMeTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.security.SpringSessionBackedSessionRegistry;

/**
 * 接口分类                        yapi 分类文件夹
 * 功能说明
 *
 * @author : 郭宗亮
 * @module 项目名称/模块名          yapi 项目组/子项目
 * @date : 2021/7/1 16:19
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomLogoutSuccessHandler logoutSuccessHandler;

    @Autowired
    private CustomSessionInformationExpiredStrategy sessionInformationExpiredStrategy;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private UserAuthenticationEntryPoint userAuthenticationEntryPoint;

    @Autowired
    private FindByIndexNameSessionRepository findByIndexNameSessionRepository;

    @Autowired
    private RememberMeTokenService rememberMeTokenService;

    @Autowired
    private LoginAuthenticationFilter loginAuthenticationFilter;

    @Autowired
    private SmsCodeAuthenticationSecurityConfig smsCodeAuthenticationSecurityConfig;

    @Autowired
    private ValidateCodeFilter validateCodeFilter;

    @Autowired
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        validateCodeFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);
        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class).apply(smsCodeAuthenticationSecurityConfig);
//        http.addFilterBefore(loginAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        //开启跨域访问
        http.cors().disable();
        //开启模拟请求，比如API POST测试工具的测试，不开启时，API POST为报403错误
        http.csrf().disable();

        http.httpBasic()
                .authenticationEntryPoint(userAuthenticationEntryPoint)
                .and().authorizeRequests()
//                .antMatchers("/doc.html", "/webjars/**", "/img.icons/**", "/swagger-resources/**", "/v2/api-docs").permitAll()
                .anyRequest().permitAll();

        http.logout()
                .logoutUrl("/user-management/auth/logout/v1").logoutSuccessHandler(logoutSuccessHandler);

        // session管理
        http.sessionManagement()
                // 最大会话数
                .maximumSessions(1)
                .expiredSessionStrategy(sessionInformationExpiredStrategy)
                //达到最大数后，强制验证，提出旧用户
                .maxSessionsPreventsLogin(false)
                .sessionRegistry(new SpringSessionBackedSessionRegistry<>(findByIndexNameSessionRepository));

        http.authorizeRequests()
                .and()
                .rememberMe()
                .rememberMeServices(rememberMeServices())
                .key("remember-me");
    }

    @Bean
    public HappokRememberMeServices rememberMeServices() {
        HappokRememberMeServices services = new HappokRememberMeServices("remember-me",
                userDetailsService, rememberMeTokenService);
        services.setTokenValiditySeconds(7 * 24 * 3600);
        return services;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 指定密码加密所使用的加密器为passwordEncoder(), 需要将密码加密后写入数据库
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
//        auth.authenticationProvider(authenticationProvider);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        // BCryptPasswordEncoder：Spring Security 提供的加密工具
        return new BCryptPasswordEncoder();
    }
}
